package ui;

import java.awt.Component;

import javax.swing.AbstractCellEditor;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableCellEditor;


/**
 * Text cell editor is a default editor to enable editing on text values
 * @author ido
 * 
 */
public class NumCellEditor extends AbstractCellEditor implements
		TableCellEditor {

	// This is the component that will handle the editing of the cell value
	JComponent component = new JTextField();

	/**
	 * This method is called when a cell value is edited by the user.
	 */
	public Component getTableCellEditorComponent(JTable table, Object value,
			boolean isSelected, int rowIndex, int vColIndex) {
		try {
			String str = ((Integer) value).toString();
			if (str.equalsIgnoreCase("0")) {
				((JTextField) component).setText("");
			}
			else {
				// Configure the component with the specified value
				((JTextField) component).setText(str);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			
		}
		// Return the configured component
		return component;
	}

	/**
	 * This method is called when editing is completed.
	 *  It must return the new value to be stored in the cell.
	 */
	public Object getCellEditorValue() {
		return ((JTextField) component).getText();
	}

	/**
	 * This method is called just before the cell value is saved. If the value
	 * is not valid, false should be returned.
	 */
	public boolean stopCellEditing() {
		String s = (String) getCellEditorValue();
		try {
				if (Integer.parseInt(s) > 9 || Integer.parseInt(s) < 0) {
					JOptionPane.showMessageDialog(null,
							"Only numbers from 0 to 9", "Opss...",
							JOptionPane.ERROR_MESSAGE);
					return true;
				}
		}
		catch (Exception ex){
			JOptionPane.showMessageDialog(null,
					"Only numbers from 0 to 9", "Opss...",
					JOptionPane.ERROR_MESSAGE);
			return true;
		}
		return super.stopCellEditing();
	}

}